<script lang="ts" setup>
import type { EvaluationType, HomeworkCardType, SubTaskType } from '@/types/micro-scene';
import ResourceList from './ResourceList.vue';
import frontIcon from "@/assets/front/front1.png";
import { BellOutlined, CheckOutlined, CloseOutlined, DeleteOutlined, EditOutlined, LinkOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons-vue';
import { computed, onMounted, ref } from 'vue';
import { useUserStore } from '@/stores/useUserStore';
import HomeworkModal from './HomeworkModal.vue';
import { Modal, message } from 'ant-design-vue';
import { getSubstateInfo, updateSubstateInfo } from '@/api/MicroScene/MicroSceneSubstateApi';
import { useRoute } from 'vue-router';
import type { SubStateCard } from '@/api/MicroScene/types/MicroSceneTypes';
import { addSubPhaseSubmittedHomeworkApi, deleteSubPhaseSubmittedHomeworkApi, getSubPhaseSubmittedHomeworkApi } from '@/api/MicroScene/MicroSceneDetailApi';
import { validateNull } from '@/utils/validate';
const props = defineProps<{
  phaseId: string
  subPhaseId: string
  beginEndId: string
}>();

const emit = defineEmits<{
  delete: [subPhaseId: string]
}>();

const userStore = useUserStore()
const route = useRoute()
const task = ref<SubTaskType>(
  {
    subPhaseId: props.subPhaseId,
    subPhaseTitle: '',
    introduction: '',
    subPhaseTarget: '',
    subPhaseWorkRequirement: '',
  },
);

const evaluation = ref<EvaluationType>({
  totalScore: 0,
  gainedScore: 0,
  homeworkComment: '',
});
// 子阶段在阶段中的排序（不修改，修改时作为参数）
const sortOrder = ref<number>(0);
// 具体任务作品模块的状态
const isModuleVisible = ref(true);

// 获取子阶段基本信息
const handleGetSubStateInfo = async () => {
  const response = await getSubstateInfo(Number(route.params.id), Number(props.subPhaseId))
  task.value.subPhaseTitle = response.subPhaseTitle
  task.value.introduction = response.introduction
  task.value.subPhaseTarget = response.subPhaseTarget
  task.value.subPhaseWorkRequirement = response.workRequirement
  evaluation.value.totalScore = response.workScore
  sortOrder.value = response.sortOrder
  isModuleVisible.value = response.workExist
}

// 修改子阶段基本信息
const handleUpdateSubstateInfo = async () => {
  const subStateCard: SubStateCard = {
    sceneId: Number(route.params.id),
    subPhaseId: Number(props.subPhaseId),
    subPhaseTitle: task.value.subPhaseTitle,
    introduction: task.value.introduction,
    subPhaseTarget: task.value.subPhaseTarget,
    workRequirement: task.value.subPhaseWorkRequirement,
    workScore: evaluation.value.totalScore,
    sortOrder: sortOrder.value,
    phaseId: Number(props.phaseId),
    workExist: isModuleVisible.value,
  }
  try {
    await updateSubstateInfo(subStateCard)
    message.success('修改成功')
  }
  catch (error) {
    message.error('修改失败')
  }
}

const handleDelete = () => {
  emit('delete', props.subPhaseId);
};

const isEdit = ref(false);
const evaluationCache = ref<EvaluationType>();
const taskCache = ref<SubTaskType>();
const showEdit = computed(() => {
  return userStore.isEditMicroScene
})
const handleEdit = () => {
  isEdit.value = true;
  // 深拷贝
  evaluationCache.value = JSON.parse(JSON.stringify(evaluation.value));
  taskCache.value = JSON.parse(JSON.stringify(task.value));
}
const handleCancel = () => {
  isEdit.value = false;
  // 深拷贝
  evaluation.value = JSON.parse(JSON.stringify(evaluationCache.value as EvaluationType));
  task.value = JSON.parse(JSON.stringify(taskCache.value as SubTaskType));
}
const handleSave = async () => {
  isEdit.value = false;
  evaluation.value.gainedScore = 0;
  evaluation.value.homeworkComment = '';
  await handleUpdateSubstateInfo();
}

const showHomeworkModal = ref(false);
const handleShowHomeworkModal = (showModal: boolean) => {
  showHomeworkModal.value = showModal;
}

// 已提交的作品列表
const submittedHomeworkList = ref<HomeworkCardType[]>([]);

// 获取已提交的作品列表
const getSubPhaseHomeworkList = async () => {
  try {
    const response = await getSubPhaseSubmittedHomeworkApi(props.beginEndId, props.subPhaseId)

    if (validateNull(response.subPhaseOpusId)) {
      submittedHomeworkList.value = []
      evaluation.value.gainedScore = 0;
      evaluation.value.homeworkComment = '';
    }
    else {
      submittedHomeworkList.value = [{
        opusId: response.subPhaseOpusId,
        opusTitle: response.opusTitle,
        introduction: response.introduction,
        score: response.score,
        remark: response.remark,
        commitTime: response.commitTime,
      }]
      evaluation.value.gainedScore = response.score;
      evaluation.value.homeworkComment = response.remark;
    }
  }
  catch (error) {
    console.error('获取已提交的作品列表失败', error);
    message.error('获取已提交的作品列表失败');
  }
}

const handleDeleteHomework = async () => {
  // 删除作品
  submittedHomeworkList.value = [];
  try {
    await deleteSubPhaseSubmittedHomeworkApi(props.beginEndId, props.subPhaseId)
  }
  catch (error) {
    console.error('删除作品失败', error);
    message.error('删除作品失败');
  }
}

// 上传作业
const handleUploadHomework = async (formData: HomeworkCardType, imgFileList: any[], homeworkFileList: any[]) => {
  try {
    await addSubPhaseSubmittedHomeworkApi(props.beginEndId, props.subPhaseId, formData.introduction || '', formData.homeworkLabel || [], formData.opusTitle || '', imgFileList[0].originFileObj, homeworkFileList[0].originFileObj)
    message.success('上传作业成功')
    getSubPhaseHomeworkList()
  }
  catch (error) {
    console.error('上传作业失败', error);
    message.error('上传作业失败');
  }
}

// 删除模块的处理函数
const handleDeleteModule = () => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除具体任务作品模块吗',
    okText: '确定',
    cancelText: '取消',
    okType: 'danger',
    onOk: async () => {
      isModuleVisible.value = false;
      evaluation.value.totalScore = 0;
      try {
        await handleUpdateSubstateInfo();
        message.success('已删除具体任务作品模块');
      }
      catch (error) {
        message.error('删除失败');
      }
    },
  });
};

// 添加模块的按钮
const handleAddModule = async () => {
  isModuleVisible.value = true;
  try {
    await handleUpdateSubstateInfo();
    message.success('已添加具体任务作品模块');
  }
  catch (error) {
    message.error('添加失败');
  }
}

onMounted(() => {
  handleGetSubStateInfo();
  getSubPhaseHomeworkList();
})
</script>

<template>
  <div class="flex gap-4 my-6">
    <div class="">
      <img :src="frontIcon" alt="frontIcon" class="w-4 h-4">
    </div>
    <div class="w-full">
      <div class="flex flex-row items-center">
        <div v-show="!isEdit" class="font-bold text-[1rem]">
          {{ task.subPhaseTitle }}
        </div>
        <a-input v-show="isEdit" v-model:value="task.subPhaseTitle" class="w-[25rem]" />
        <div class="flex gap-8 items-center ml-4">
          <!-- 标题编辑区域 -->
          <div v-if="showEdit">
            <a-button v-show="!isEdit" type="text" @click="handleEdit">
              <template #icon>
                <EditOutlined />
              </template>
            </a-button>

            <a-button v-show="!isEdit" danger type="text" @click="handleDelete">
              <template #icon>
                <DeleteOutlined />
              </template>
            </a-button>

            <a-button v-show="isEdit" @click="handleCancel">
              <template #icon>
                <CloseOutlined />
              </template>
            </a-button>
            <a-button v-show="isEdit" type="primary" @click="handleSave">
              <template #icon>
                <CheckOutlined />
              </template>
            </a-button>
          </div>
        </div>
      </div>

      <div class="my-4">
        <div class="text-[0.875rem] font-bold mb-2">
          任务介绍
        </div>
        <div v-show="!isEdit" class="text-[0.875rem] leading-6 whitespace-pre-wrap">
          {{ task.introduction }}
        </div>
        <a-textarea
          v-show="isEdit" v-model:value="task.introduction" :auto-size="{ minRows: 3, maxRows: 10 }"
          class="w-full"
        />
      </div>
      <div class="my-4">
        <div class="text-[0.875rem] font-bold mb-2">
          任务目标
        </div>
        <div v-show="!isEdit" class="text-[0.875rem] leading-6 whitespace-pre-wrap">
          {{ task.subPhaseTarget }}
        </div>
        <a-textarea
          v-show="isEdit" v-model:value="task.subPhaseTarget" :auto-size="{ minRows: 3, maxRows: 10 }"
          class="w-full"
        />
      </div>
      <div class="my-4">
        <!-- 任务资源 -->
        <ResourceList :phase-id="props.phaseId" :sub-phase-id="props.subPhaseId" />
      </div>
      <!-- 作品模块 -->
      <div v-if="isModuleVisible">
        <div class="my-4">
          <div class="flex items-center">
            <div class="text-[0.875rem] font-bold mr-4">
              作品要求
            </div>
            <div v-if="showEdit">
              <a-button type="text" danger @click="handleDeleteModule">
                <template #icon>
                  <DeleteOutlined />
                </template>
              </a-button>
            </div>
          </div>

          <div v-show="!isEdit" class="text-[0.875rem] leading-6 whitespace-pre-wrap mt-2">
            {{ task.subPhaseWorkRequirement }}
          </div>
          <a-textarea
            v-show="isEdit" v-model:value="task.subPhaseWorkRequirement" :auto-size="{ minRows: 3, maxRows: 10 }"
            class="w-full mt-2"
          />
        </div>
        <!-- 提交作品部分 -->
        <div v-if="isModuleVisible" class="my-2 gap-2">
          <a-button type="primary" @click="handleShowHomeworkModal(true)">
            提交作品
            <template #icon>
              <UploadOutlined />
            </template>
          </a-button>
          <!-- 已经提交的作品列表 -->
          <a-list :data-source="submittedHomeworkList">
            <template #renderItem="{ item }">
              <a-list-item class="text-blue-500 select-none">
                <div class="flex items-center justify-between">
                  <LinkOutlined />
                  <span class="text-blue-500 ml-2">
                    {{ `${item.opusTitle} ${item.commitTime}` }}
                  </span>
                  <a-button
                    type="primary" danger size="small" class="text-xs ml-4"
                    @click="handleDeleteHomework"
                  >
                    <template #icon>
                      <DeleteOutlined class="text-xs" />
                    </template>
                  </a-button>
                </div>
              </a-list-item>
            </template>
          </a-list>
        </div>
        <HomeworkModal :show-modal="showHomeworkModal" @update:show-modal="handleShowHomeworkModal" @upload-homework="handleUploadHomework" />
        <!-- 作业评价 -->
        <div class="my-4">
          <div class="text-[0.875rem] font-bold mb-2">
            作品评价
          </div>
          <div v-show="!isEdit" class="text-[0.875rem] leading-6">
            本次作品总分：{{ evaluation.totalScore }} 分
          </div>
          <div v-show="!isEdit" class="text-[0.875rem] leading-6">
            已获得 {{ evaluation.gainedScore }} 分
          </div>
          <div v-show="!isEdit" class="text-[0.875rem] leading-6 whitespace-pre-wrap">
            {{ evaluation.homeworkComment }}
          </div>
          <!-- 编辑模式 -->
          <div v-show="isEdit" class="flex items-center my-4">
            <span class="text-[0.875rem]">该阶段总分数：</span>
            <a-input v-model:value="evaluation.totalScore" class="w-32" placeholder="请输入总分" />
            <span class="text-[0.875rem] ml-2">分</span>
          </div>
        </div>
      </div>
      <div v-else>
        <div class="flex items-center justify-center h-full">
          <a-button type="primary" @click="handleAddModule">
            添加具体任务作品模块
            <template #icon>
              <PlusOutlined />
            </template>
          </a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>
